package com.lhkj.ct.framework.filter;

import com.lhkj.ct.framework.shiro.session.ShiroSessionManager;
import com.lhkj.ct.framework.shiro.token.UsernamePasswordAuthToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * apidoc文档自动登录
 */
public class Knif4jAuthBasicAuthFilter implements Filter {

    private static final Logger log = LoggerFactory.getLogger(Knif4jAuthBasicAuthFilter.class);

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException {
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()) {
            String username = "root";
            String password = "15625260623";
            UsernamePasswordAuthToken token = new UsernamePasswordAuthToken(username, password, true);
            token.setUserType(1);
            token.setNoPassword(false);
            try {
                  subject.login(token);
                System.out.println("登录成功");
            } catch (AuthenticationException e) {

                if (e instanceof UnknownAccountException) {

                    System.out.println("用户不存在");

                } else if (e instanceof IncorrectCredentialsException) {

                    System.out.println("密码不正确");

                } else if (e instanceof LockedAccountException) {

                    System.out.println("用户账号被锁定");

                } else {

                    System.out.println("认证失败");

                }
            }
            ;
        }
        String projectName = servletRequest.getServletContext().getContextPath();
        String sessionId = subject.getSession(false).getId().toString();
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        StringBuilder builder = new StringBuilder();
        builder.append(ShiroSessionManager.HEADER_TOKEN_NAME).append("=").append(sessionId).append(";");
        builder.append("path=").append(projectName).append(";");
        if ("https".equalsIgnoreCase(servletRequest.getScheme())) {
            builder.append("secure;");
        }
        builder.append("HttpOnly;");
        httpServletResponse.setHeader("Set-Cookie", builder.toString());
        chain.doFilter(servletRequest, servletResponse);
    }
}
